﻿using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using BasicModuleWebApiJWTAuthorization.Model;

namespace BasicModuleWebApiJWTAuthorization.PermissionAuthorization
{
    public class UserPermissionAuthodrizationHandler : AuthorizationHandler<UserPermissionAuthorizationRequirement>
    {

        public UserPermissionAuthodrizationHandler()
        {
        }

        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, UserPermissionAuthorizationRequirement requirement)
        {
            #region 动态配置
            {
                ////获取用户请求的接口
                //bool bl = context.Resource is DefaultHttpContext;
                ////开始鉴权
                //if (bl == true)
                //{

                //}
                //else
                //    context.Succeed(requirement);

                IEnumerable<Claim> claimsPrincipal = context.User.Claims;
                if (context.User?.Identity?.IsAuthenticated != true)
                {
                    context.Fail(new AuthorizationFailureReason(this, "请求失败"));
                    return;
                }
                //var str = claimsPrincipal.Where(x => x.Type == "UserId").FirstOrDefault();
                //if (str == null)
                //{
                //    context.Fail(new AuthorizationFailureReason(this, "请求失败"));
                //    return;
                //}
                //int UserId = int.Parse(str.Value);
                //string policy = requirement.PolicyName;
                //可以将用户权限缓存到redis 或者微软扩展缓存
                //DefaultHttpContext defaultHttpContext = context.Resource as DefaultHttpContext;
                //string path = defaultHttpContext.Request.Path;
                context.Succeed(requirement);

            }
            #endregion
        }
    }
}
